<?php
#TODO: rewrite this shit @_@

class pagger extends service{
	public $per_page = 15;
	public $pagger_page = 1;
	
		public function __construct(){
			$this->db = context::get("db");
		}

		public function fetch_cached($timeout, $select, $from, $where, $order_by = null){
			return $this->fetch_query($select, $from, $where, $order_by=null);
		}
	
		public function set_page($page_id){
			$this->page_id = $page_id;
		}
		
		public function set_db($db){
			$this->db = $db;
		}
	
		public function get_query($select, $from, $where, $order_by=null, $group_by = null){
			$where = $where ? $where : "TRUE";
			$this->per_page = $this->per_page ? $this->per_page : 15;
			
			$query = "SELECT count(*) entries_count FROM ".$from." WHERE ".$where.";";
			$arr = $this->db->fetch_array($query);
			
			$this->entries_count = $arr[0]["entries_count"];
			$this->page_count = (int)($this->entries_count / $this->per_page ) + 1 ;

			
			if (!isset($this->page_id)){$this->page_id = 1;}
			
			
			
			
			$this->set_tpl_vars();
			
			$query = "SELECT 
			".$select."	
			FROM
			".$from."
			
			WHERE
			".$where."
			";
			
			if ($group_by) {
				$query .= "
				GROUP BY {$group_by}
				";
			}
			
			if ($order_by) {
				$query .= "
				ORDER BY ".$order_by."
				";
			}
			
			$query .="
			LIMIT ".$this->per_page."
			OFFSET ".($this->per_page * ($this->page_id-1))."
			
			";
			
			return $query;
		}
	
		public function fetch_query($select, $from, $where, $order_by=null, $group_by = null){
			$query = $this->get_query($select, $from, $where, $order_by, $group_by);
			$arr = $this->db->fetch_array($query);
			
			return $arr;
		}
		
		public function set_tpl_vars(){
			$tpl = context::get("tpl");
			
			$tpl->assign("pagger_page",$this->pagger_page);
			$tpl->assign("pagger_enries_count",$this->entries_count);
			$tpl->assign("pagger_page_count",$this->page_count);
			$tpl->assign("pagger_page_id",$this->page_id);
		}
	
}

?>
